Component({
    data: {
        hasFaceRegistered: false,
        showFaceRegisterModal: false,
        upcomingCheckins: [],
        courses: [],
        showJoinClassModal: false,
        classCode: ''
    },

    lifetimes: {
        attached() {
            this.checkFaceRegistration();
            this.loadUpcomingCheckins();
            this.loadCourses();
        }
    },

    pageLifetimes: {
        show() {
            this.checkFaceRegistration();
            this.loadUpcomingCheckins();
            this.loadCourses();
        }
    },

    methods: {
        // 检查学生是否已注册人脸
        checkFaceRegistration() {
            const hasFaceRegistered = wx.getStorageSync('hasFaceRegistered') || false;
            this.setData({
                hasFaceRegistered: hasFaceRegistered
            });
        },

        // 加载即将开始的签到
        loadUpcomingCheckins() {
            const userInfo = wx.getStorageSync('userInfo');
            if (!userInfo || !userInfo.userId) {
                console.error('未获取到用户信息');
                return;
            }

            wx.showLoading({
                title: '加载中...',
            });

            getStudentUpcomingCheckin(userInfo.userId)
                .then(res => {
                    wx.hideLoading();
                    if (res.data) {
                        this.setData({
                            upcomingCheckins: [res.data],
                        });
                    } else {
                        this.setData({
                            upcomingCheckins: [],
                        });
                    }
                })
                .catch(err => {
                    wx.hideLoading();
                    console.error('获取签到信息失败:', err);
                    wx.showToast({
                        title: '获取签到信息失败',
                        icon: 'none'
                    });
                    this.setData({
                        upcomingCheckins: []
                    });
                });
        },

        // 加载学生课程
        loadCourses() {
            const userInfo = wx.getStorageSync("userInfo");
            if (userInfo.role === 2) {
                getStudentCourseList(userInfo.userId)
                    .then((res) => {
                        this.setData({
                            courses: res.data.map((item) => ({
                                courseId: item.courseId,
                                courseName: item.courseName,
                            })),
                        });
                    })
                    .catch((err) => {
                        console.error("获取学生课程列表失败:", err);
                        wx.showToast({
                            title: "获取课程列表失败",
                            icon: "none",
                        });
                    });
            }
        },

        // 执行签到操作
        doCheckin(e) {
            const checkin = this.data.upcomingCheckins[0];
            const userInfo = wx.getStorageSync("userInfo");
            
            if (!userInfo.imageUrl || userInfo.imageUrl === "") {
                this.setData({
                    showFaceRegisterModal: true,
                });
                return;
            }

            const currentTime = new Date();
            const checkinStartTime = new Date(checkin.startTime);
            
            if (currentTime > checkinStartTime) {
                wx.showToast({
                    title: '签到时间已过',
                    icon: 'none'
                });
                return;
            }

            studentSignin(userInfo.userId, checkin.id)
                .then(res => {
                    wx.showToast({
                        title: res.data,
                        icon: 'success',
                        duration: 1500
                    });

                    setTimeout(() => {
                        this.loadUpcomingCheckins();
                    }, 1500);
                })
                .catch(err => {
                    console.error('签到失败:', err);
                    wx.showToast({
                        title: err.message || '签到失败',
                        icon: 'none'
                    });
                });
        },

        // 查看课程签到详情
        viewCourseCheckins(e) {
            wx.setStorageSync('courseInfo', e.currentTarget.dataset.item);
            wx.navigateTo({
                url: `/pages/student_course_checkin/student_course_checkin`
            });
        },

        // 关闭人脸注册提示弹窗
        closeFaceModal() {
            this.setData({
                showFaceRegisterModal: false
            });
        },

        // 前往人脸注册页面
        goToFaceRegister() {
            wx.navigateTo({
                url: '/pages/face_register/face_register'
            });
            this.setData({
                showFaceRegisterModal: false
            });
        },

        // 显示加入班级弹窗
        showJoinClassModal() {
            this.setData({
                showJoinClassModal: true,
                classCode: ''
            });
        },

        // 关闭加入班级弹窗
        closeJoinClassModal() {
            this.setData({
                showJoinClassModal: false
            });
        },

        // 加入班级
        joinClass() {
            const classCode = this.data.classCode;
            if (!classCode || classCode.trim() === '') {
                wx.showToast({
                    title: '请输入班级编码',
                    icon: 'none'
                });
                return;
            }

            const userInfo = wx.getStorageSync('userInfo');
            if (!userInfo || !userInfo.userId) {
                console.error('未获取到用户信息');
                wx.showToast({
                    title: '未获取到用户信息',
                    icon: 'none'
                });
                return;
            }

            wx.showLoading({
                title: '正在加入班级...',
            });

            joinClass(userInfo.userId, classCode.trim())
                .then(res => {
                    wx.hideLoading();
                    wx.showToast({
                        title: '加入班级成功',
                        icon: 'success',
                        duration: 2000
                    });
                    this.setData({
                        showJoinClassModal: false
                    });
                    setTimeout(() => {
                        this.loadCourses();
                    }, 1000);
                })
                .catch(err => {
                    wx.hideLoading();
                    console.error('加入班级失败:', err);
                    wx.showToast({
                        title: err.message || '加入班级失败',
                        icon: 'none',
                        duration: 2000
                    });
                });
        },

        navigateToCheckinPage(e) {
            const courseId = e.currentTarget.dataset.courseid;
            wx.navigateTo({
                url: `/pages/student_course_checkin/student_course_checkin?courseId=${courseId}`,
            });
        }
    }
}); 